package com.example.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.AirQualitySensor;
import com.example.entity.Params;
import com.example.repository.AirQualitySensorMapper;
import com.example.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AirQualitySensorService extends ServiceImpl<AirQualitySensorMapper, AirQualitySensor> {

    @Resource
    private AirQualitySensorMapper airQualitySensorMapper;


    public PageInfo<AirQualitySensor> getSensorData(Params params){
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<AirQualitySensor> search = airQualitySensorMapper.getSensorData();
        return PageInfo.of(search);
    }

    public void addAQS(AirQualitySensor airQualitySensor) {
        airQualitySensorMapper.insert(airQualitySensor);
    }

    public void deleteAQS(Long id) {
        airQualitySensorMapper.deleteById(id);
    }


    //每30分钟计算一次
    public double getHCHO() {

        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MINUTE, -20);
        Date twentySecondsAgo = calendar.getTime();
        return airQualitySensorMapper.selectList(Wrappers.<AirQualitySensor>lambdaQuery().between(
                        AirQualitySensor::getCreateTime, DateUtil.date2Str(twentySecondsAgo), DateUtil.date2Str(now)))
                .stream().mapToInt(AirQualitySensor::getHCHO).average().orElse(0);
    }

    public Map<String, Object> initLine(Params params) {

        List<Map<String, Object>> rawList = airQualitySensorMapper.initLine(params);
        // 固定时间段（x轴）
        List<String> xAxis = generateXAxis(params.getInterval());
        List<Integer> yAxis = new ArrayList<>(Collections.nCopies(xAxis.size(), 0));  // 默认全部为0
        // 建立时间段与索引映射
        Map<String, Integer> indexMap = new HashMap<>();
        for (int i = 0; i < xAxis.size(); i++) {
            indexMap.put(xAxis.get(i), i);
        }
        // 用返回结果更新对应位置的值
        for (Map<String, Object> row : rawList) {
            String timeGroup = (String) row.get("time_group");
            Number avg = (Number) row.get("avg_hcho");
            int value = (avg != null) ? (int) Math.floor(avg.doubleValue()) : 0;

            Integer idx = indexMap.get(timeGroup);
            if (idx != null) {
                yAxis.set(idx, value);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", xAxis);
        result.put("yAxis", yAxis);
        return result;
    }

    // 补充生成xAxis的方法
    private List<String> generateXAxis(int interval) {
        List<String> xAxis = new ArrayList<>();
        for (int i = 0; i < 24; i += interval) {
            xAxis.add(String.format("%02d:00", i));
        }
        xAxis.add("24:00"); // 补上24:00作为最后一个点
        return xAxis;
    }

    public Map<String, Object> initLineForAdmin(Params params) {
        List<Map<String, Object>> rawList = airQualitySensorMapper.initLineForAdmin(params);

        // 调用封装的方法
        List<String> dateLabels = generateLastNDaysLabels(params.getPast());
        List<Integer> hcholist = new ArrayList<>(Collections.nCopies(dateLabels.size(), 0));

        Map<String, Integer> dateIndexMap = new HashMap<>();
        for (int i = 0; i < dateLabels.size(); i++) {
            dateIndexMap.put(dateLabels.get(i), i);
        }

        for (Map<String, Object> row : rawList) {
            String date = String.valueOf(row.get("date"));
            Integer hcho = ((Number) row.get("avg_hcho")).intValue();

            Integer idx = dateIndexMap.get(date);
            if (idx != null) {
                hcholist.set(idx, hcho);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("xAxis", dateLabels);
        result.put("yAxis", hcholist);
        return result;
    }

    private List<String> generateLastNDaysLabels(int n) {
        List<String> dateLabels = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = n - 1; i >= 0; i--) {
            cal.setTime(new Date());
            cal.add(Calendar.DAY_OF_MONTH, -i);
            dateLabels.add(sdf.format(cal.getTime()));
        }
        return dateLabels;
    }

}
